import { _decorator, Component, Node, ToggleContainer, resources, SpriteFrame, Sprite, Prefab, instantiate, sys, director, EventHandler, Toggle, find } from 'cc';
import { Board, setLimitDepth } from "./Board";
import { GameData } from "./framework/GameData";
import { MiniGameSdk } from '../Sdk/MiniGameSdk';
import { bdlMgr } from 'db://assets/Script/Manager/BundleManager_S';
import { SSS_AudioManager } from 'db://assets/Script/Manager/SSS_AudioManager';
import Xiangqi_DifficultyPanel from './Xiangqi_DifficultyPanel';
const { ccclass, property } = _decorator;

@ccclass('ChessBoard')
export class ChessBoard extends Component {
    board: Board;

    @property(Node)
    Button_back: Node | null = null;
    @property(Node)
    Button_refresh: Node | null = null;

    @property(Node)
    悔棋: Node | null = null;

    // @property(ToggleContainer)
    // ToggleContainer_难度: ToggleContainer | null = null;


    @property(Node)
    boardNode: Node = null!;

    @property(Node)
    modeListNode: Node = null!;

    // @property(Node)
    // levelListNode: Node = null!;

    AddListener() {
        this.Button_back.on(Node.EventType.TOUCH_END, this.On_Button_back, this);
        this.Button_refresh.on(Node.EventType.TOUCH_END, this.On_Button_refresh, this);
        this.悔棋.on(Node.EventType.TOUCH_END, this.onClickRetract, this);

        // this.ToggleContainer_难度.node.on(Node.EventType.TOUCH_END, this.选择难度, this);

        console.log("AddListener----------");

        // const toggles = this.ToggleContainer_难度.node.getComponentsInChildren(Toggle);
        // for (const toggle of toggles) {
        //     toggle.node.on('toggle', this.onToggleChanged, this);
        // }
    }

    // onToggleChanged(toggle: Toggle) {
    //     // console.log('被点击的 Toggle：', toggle.node.name);

    //     // 获取当前容器中已选中的 Toggle
    //     // const toggles = this.ToggleContainer_难度.node.getComponentsInChildren(Toggle);
    //     // const checked = toggles.find(t => t.isChecked);

    //     if (toggle.isChecked) {
    //         // console.log('当前选中的 Toggle 是：', checked?.node.name);
    //         console.log('当前选中的 Toggle 是：', toggle?.node.name);

    //         // const toggles = this.ToggleContainer_难度.node.getComponentsInChildren(Toggle);

    //         // 找出当前 toggle 在数组中的索引
    //         // const index = toggles.indexOf(toggle);

    //         // let depth = index + 1;
    //         // depth = Math.pow(2, depth);
    //         // console.log("depth==", index, depth);
    //         // setLimitDepth(depth);
    //     }

    //     // // 获取当前选择的项
    //     // let toggleItems = toggleContainer.toggleItems;
    //     // for (let i = 0; i < toggleItems.length; i++) {
    //     //     let toggle = toggleItems[i];
    //     //     if (toggle.isChecked) {
    //     //         // 当前选中的项
    //     //         console.log("当前选择的项索引为：" + i);
    //     //         // idx = i;
    //     //         break;
    //     //     }
    //     // }
    // }

    // 选择难度(event: Event, customEventData: string) {
    //     console.log('ToggleContainer 被点击了');

    //     let idx = 0;

    //     // 获取 ToggleContainer 组件
    //     // let toggleContainer = this.ToggleContainer_难度.getComponent(ToggleContainer);

    //     // 获取当前选择的项
    //     // let toggleItems = toggleContainer.toggleItems;
    //     // for (let i = 0; i < toggleItems.length; i++) {
    //     //     let toggle = toggleItems[i];
    //     //     if (toggle.isChecked) {
    //     //         // 当前选中的项
    //     //         console.log("当前选择的项索引为：" + i);
    //     //         idx = i;
    //     //         break;
    //     //     }
    //     // }

    //     let depth = idx + 1;
    //     depth = Math.pow(2, depth);
    //     console.log("depth==", depth);
    //     setLimitDepth(depth);
    // }

    RemoveListener() {
        this.Button_back.off(Node.EventType.TOUCH_END, this.On_Button_back, this);
        this.Button_refresh.off(Node.EventType.TOUCH_END, this.On_Button_refresh, this);
    }

    On_Button_back() {
        director.loadScene("MainScene");

        SSS_AudioManager.PlayButtonAudio();
    }

    On_Button_refresh() {
        this.onClickRestart();

        SSS_AudioManager.PlayButtonAudio();
    }

    ShowOn() {
        this.node.active = true;
        this.AddListener();
    }

    onLoad() {
        this.ShowOn();
    }

    start() {
        let board = new Board(this.boardNode, this.gameOver.bind(this))
        this.board = board
        board.setSearch(16);
        board.millis = 1000;// 思考时间毫秒
        board.computer = 1;

        if (GameData.getInstance().matchId) {
            // this.modeListNode.active = false;
            // this.levelListNode.active = false;

            // 残棋
            setLimitDepth(Math.pow(2, 4));//深度更高会卡死!!!
        } else {
            // this.modeListNode.active = true;
            // this.levelListNode.active = true;

            Xiangqi_DifficultyPanel.Instance.难度_index = 2;
            Xiangqi_DifficultyPanel.Instance.updateButtonHighlights();

            let depth = Xiangqi_DifficultyPanel.Instance.难度_index + 1;
            depth = Math.pow(2, depth);
            console.log("depth==", Xiangqi_DifficultyPanel.Instance.难度_index, depth);
            // 人机对弈
            setLimitDepth(depth);

            // setLimitDepth(2);
        }
    }

    update(deltaTime: number) {

    }

    gameOver(result: number) {
        // 加载预制
        // const prefab = bdlMgr.getRes<Prefab>(`S2048_Prefab`, `Grid`, Prefab);

        // resources.load("prefab/matchResult", Prefab, (err, prefab: Prefab) => {
        bdlMgr.getRes<Prefab>(`Xiangqi_Prefab`, `matchResult`, Prefab).then(prefab => {
            let nodePrefab = instantiate(prefab)
            this.node.addChild(nodePrefab)

            //关闭按钮
            let btnClose = nodePrefab.getChildByName("root").getChildByName("btnClose")
            btnClose.on('click', () => {
                nodePrefab.removeFromParent()
            });

            //图片
            // let imgResult = nodePrefab.getChildByName("root").getChildByName("imgResult")
            // let images = "images/"
            // let resultImage = ""
            // if (result == 1) {
            //     resultImage = "win"
            // } else if (result == -1) {
            //     resultImage = "lose"
            // } else if (result == 0) {
            //     resultImage = "draw"
            // }

            // // resources.load(images + resultImage + "/spriteFrame", SpriteFrame, (err, spriteFrame: SpriteFrame) => {
            // bdlMgr.getRes<SpriteFrame>(`Xiangqi_Sprite`, images + resultImage + "/spriteFrame", SpriteFrame).then(spriteFrame => {
            //     imgResult.getComponent(Sprite).spriteFrame = spriteFrame
            // })

            let imgResult = nodePrefab.getChildByName("root").getChildByName("imgResult")
            let 胜利 = find(`胜利`, imgResult);
            let 失败 = find(`失败`, imgResult);
            let 平局 = find(`平局`, imgResult);
            胜利.active = false;
            失败.active = false;
            平局.active = false;
            if (result == 1) {
                胜利.active = true;
            } else if (result == -1) {
                失败.active = true;
            } else if (result == 0) {
                平局.active = true;
            }
        })
    }

    onClickRestart() {
        // 重新开始
        console.log("onClickRestart");
        this.board.restart_click();
    }

    onClickRetract() {
        // 悔棋
        console.log("onClickRetract");
        MiniGameSdk.AdvertManager.instance.showVideo('2dvmhdp9j595a4b3bj', (res: MiniGameSdk.EAdVideoResult, count: number) => {
            console.log('用户看的视频广告个数是:', count); //微信平台只有1个或0个，抖音平台就可能有很多个，开发者可根据个数奖励
            switch (res) {
                case MiniGameSdk.EAdVideoResult.ACCEPT:
                    MiniGameSdk.API.showToast('用户看完广告,悔棋成功');
                    this.board.retract();
                    break;
                case MiniGameSdk.EAdVideoResult.REJECT:
                    MiniGameSdk.API.showToast('拒绝掉了广告,悔棋失败');
                    break;
                case MiniGameSdk.EAdVideoResult.ERROR:
                    MiniGameSdk.API.showToast('播放广告发生错误,悔棋失败');
                    break;
                default:
                    break;
            }
        });

    }

    onClickMode(sender, eventType) {
        console.log("onClickMode");

        let idx = 0;

        // 获取 ToggleContainer 组件
        let toggleContainer = sender.node.parent.getComponent(ToggleContainer);

        // 获取当前选择的项
        let toggleItems = toggleContainer.toggleItems;
        for (let i = 0; i < toggleItems.length; i++) {
            let toggle = toggleItems[i];
            if (toggle.isChecked) {
                // 当前选中的项
                console.log("当前选择的项索引为：" + i);
                idx = i;
                break;
            }
        }

        this.board.selMoveMode_click(idx);
    }

    onClickLevel(sender, eventType) {
        console.log("onClickLevel");

        let idx = 0;

        // 获取 ToggleContainer 组件
        let toggleContainer = sender.node.parent.getComponent(ToggleContainer);

        // 获取当前选择的项
        let toggleItems = toggleContainer.toggleItems;
        for (let i = 0; i < toggleItems.length; i++) {
            let toggle = toggleItems[i];
            if (toggle.isChecked) {
                // 当前选中的项
                console.log("当前选择的项索引为：" + i);
                idx = i;
                break;
            }
        }

        let depth = idx + 1;
        depth = Math.pow(2, depth);
        console.log("depth==", depth);
        setLimitDepth(depth);
    }

    onClickReturn() {
        // 先销毁
        this.node.removeFromParent();

        // 隐藏主界面
        let mainui = GameData.getInstance().rootNode.getChildByName("mainui");
        mainui.active = true;
    }
}

